package com.example.healkep.utils;

import android.app.Activity;

import com.example.healkep.LoginActivity;
import com.example.healkep.listener.HttpListener;
import com.google.gson.Gson;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HttpUtil<T> {

    public static Response post(String url, RequestBody requestBody) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .post(requestBody)
                .url(LoginActivity.url+url)
                .build();
        Call call = client.newCall(request);
        return call.execute();
    }

    public static Response get(String url) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .get()
                .url(url)
                .build();
        Call call = client.newCall(request);
        return call.execute();
    }

    public static final int TIME_OUT  = 100;
    public static final int BODY_NULL = 101;

    /**
     * 以post请求携带requestBody访问url，
     * @param url 访问地址
     * @param requestBody 请求参数
     * @param listener 监听接口，当且仅当http状态码为200且结果码为 OK 时调用success方法，否则调用failed方法
     * @param type T的type对象
     * @param activity 当前Activity对象
     */
    public void post(@NotNull String url, @NotNull RequestBody requestBody, @NotNull HttpListener<T> listener,
                     @NotNull Type type, Activity activity){
        new Thread(()->{
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .post(requestBody)
                    .url(url)
                    .build();
            Call call = client.newCall(request);
            try {
                Response response = call.execute();
                if(response.code()!=200){
                    activity.runOnUiThread(()->{
                        listener.failed(response.code(), "网络异常，请重试","访问服务器接口失败，请检查api是否正确");
                    });
                }else{
                    if(response.body()==null){
                        activity.runOnUiThread(()-> {
                            listener.failed(BODY_NULL, "网络异常，请重试", "请求体为NULL，请检查接口调用是否正确");
                        });
                    }else{
                        String json = Objects.requireNonNull(response.body()).string();
                        RespResult<T> result = new RespResult<>(json,type);
                        if(result.isOk()){
                            activity.runOnUiThread(()->{
                                listener.success(result.getData());
                            });
                        }else {
                            activity.runOnUiThread(()-> {
                                listener.failed(result.getCode(), result.getMessage(), result.getDetailMessage());
                            });
                        }
                    }
                }
            } catch (IOException e) {
                activity.runOnUiThread(()-> {
                    listener.failed(TIME_OUT, "网络异常，请重试", "连接超时");
                });
                e.printStackTrace();
            }
        }).start();
    }

    //    public RequestBody getRequestBody(Map<String,Object> map){
//        Gson gson = new Gson();
//        MediaType mediaType = MediaType.parse("application/json; charset=UTF-8");
//        return RequestBody.create(gson.toJson(map),mediaType);
//    }
    public RequestBody getRequestBody(Object obj){
        Gson gson = new Gson();
        MediaType mediaType = MediaType.parse("application/json; charset=UTF-8");
        return RequestBody.create(gson.toJson(obj),mediaType);
    }
}
